#!/bin/bash

# 脚本信息
echo "Dragonwell21(Java21)安装脚本"
echo "作者: Zeruns"
echo "博客: https://blog.zeruns.tech/"

# 检测已有Java安装
if command -v java >/dev/null 2>&1; then
    echo "检测到已安装Java。"
    read -p "是否需要卸载已有Java并清理环境变量? [y/N] " uninstall_java
    case $uninstall_java in
        [Yy]*)
            # 清理环境变量
            sed -i '/JAVA_HOME/d' /etc/profile
            sed -i '/PATH=/s/:\/usr\/local\/java\/bin://g' /etc/profile
            source /etc/profile
            
            # 删除默认的Java安装目录（需根据实际情况调整）
            rm -rf /usr/local/java/*
            echo "已卸载旧Java版本并清理环境变量。"
            ;;
        *)
            echo "保留现有Java安装，退出安装程序。"
            exit 0
            ;;
    esac
else
    echo "未检测到已安装Java，继续安装过程。"
fi

# 检测系统架构
arch=$(uname -m)
echo "检测到系统架构: $arch"

# 根据架构设置下载URL
case $arch in
    x86_64|x86)
        url1="http://123pan.zeruns.tech/down/JDK/Alibaba_Dragonwell_Standard_21.0.3.0.3.9_x64_linux.tar.gz"
        url2="https://tc3.zeruns.tech/down/JDK/Alibaba_Dragonwell_Standard_21.0.3.0.3.9_x64_linux.tar.gz"
        ;;
    aarch64) # 这里代表64位ARM
        url1="http://123pan.zeruns.tech/down/JDK/Alibaba_Dragonwell_Standard_21.0.3.0.3.9_aarch64_linux.tar.gz"
        url2="https://tc3.zeruns.tech/down/JDK/Alibaba_Dragonwell_Standard_21.0.3.0.3.9_aarch64_linux.tar.gz"
        ;;
    *)
        echo "不支持的架构: $arch"
        exit 1
        ;;
esac

# 随机选择一个初始下载URL
if [ $((RANDOM % 2)) -eq 0 ]; then
    download_url=$url1
    other_url=$url2
else
    download_url=$url2
    other_url=$url1
fi
echo "初次选定的下载链接: $download_url"

# 使用wget下载并显示进度
wget --progress=dot:giga "$download_url" -O /tmp/jdk_package.tar.gz && download_success=true
if [ $? -ne 0 ]; then
    echo "初次下载失败，尝试使用备用链接..."
    wget --progress=dot:giga "$other_url" -O /tmp/jdk_package.tar.gz && download_success=true
fi

if [ "$download_success" = true ]; then
    echo "下载完成"
else
    echo "下载仍然失败，请检查网络或手动下载安装包。"
    exit 1
fi

# 创建安装目录
mkdir -p /usr/local/java/
echo "创建安装目录完成"

# 解压到安装目录
tar -xzf /tmp/jdk_package.tar.gz -C /usr/local/java/
echo "解压完成"

# 获取解压后的目录名
jdk_folder=$(ls -d /usr/local/java/* | head -n 1)
echo "解压得到的JDK目录: $jdk_folder"

# 安装后配置环境变量（确保覆盖旧配置）
echo "export JAVA_HOME=$jdk_folder" >> /etc/profile
echo 'export PATH=$JAVA_HOME/bin:$PATH' >> /etc/profile
source /etc/profile

# 配置环境变量软链接
ln -sf "$jdk_folder/bin/java" /usr/bin/java
echo "配置环境变量完成"

# 测试安装
java -version
if [ $? -eq 0 ]; then
    echo "Java安装成功！"
else
    echo "Java安装可能存在问题，请检查错误信息。"
fi

# 添加清理临时文件
rm /tmp/jdk_package.tar.gz
echo "清理临时文件完成"

# 脚本结束提示
echo "脚本执行完毕。"